package cn.zc.utils;

import cn.zc.entity.Cource;
import cn.zc.entity.ErrCources;
import cn.zc.exception.CouceErrorException;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class StringUtils {
    /**
     * 从字符串提取课程信息
     * @param string
     * @return List<Cource>
     */
    public static ErrCources extractScheduleInfo(String string) {
        List<Cource> courceList = new ArrayList<>();
        List<String> parts = splitString(string);
        List<Integer> errweekList = new ArrayList<>();
        int day=-1;
        for (String str : parts) {
            try{
            Cource cource = new Cource();
            String[] weekParts = str.split("[，,.]");

            // 提取星期几
            String weekPart = weekParts[1];
            String dayOfWeek = String.valueOf(weekPart.charAt(weekPart.indexOf("周") + 1));
            boolean s=true;
            switch (dayOfWeek) {
                case "一", "—":
                    day = 1;
                    s=false;
                    break;
                case "二":
                    day = 2;
                    s=false;
                    break;
                case "三":
                    day = 3;
                    s=false;
                    break;
                case "四":
                    day = 4;
                    s=false;
                    break;
                case "五":
                    day = 5;
                    s=false;
                    break;
//                case "六":
//                    day = 6;
//                    break;
//                case "日":
//                    day = 7;
//                    break;
                default:
                    s=true;
            }
            if(s){
                continue;
            }
            cource.setDayOfWeek(day);
            if(day==-1){
                cource.setDayOfWeek(1);
            }
            // 提取周数
            String weekInfo = weekParts[0];
            List<Integer> weeks = new ArrayList<>();
            if (weekInfo.startsWith("单")) {
                cource.setWeekType(1);
                String[] range = weekInfo.substring(1).split("-");
                int start = Integer.parseInt(range[0]);
                int end = Integer.parseInt(range[1]);
                if(start<0 || end>16){
                    errweekList.add(day);
                    continue;
                }
                for (int i = start; i <= end; i++) {
                    if (i % 2!= 0) {
                        weeks.add(i);
                    }
                }
            } else if (weekInfo.startsWith("双")) {
                cource.setWeekType(2);
                String[] range = weekInfo.substring(1).split("-");
                int start = Integer.parseInt(range[0]);
                int end = Integer.parseInt(range[1]);
                if(start<0 || end>16){
                    errweekList.add(day);
                    continue;
                }
                for (int i = start; i <= end; i++) {
                    if (i % 2 == 0) {
                        weeks.add(i);
                    }
                }
            } else {
                cource.setWeekType(0);
                String[] range = new String[2];
                int start =0;
                int end =0;
                if (weekInfo != null && weekInfo.contains("-")) {
                     range = weekInfo.split("-");
                }
                if (!weekInfo.contains("-")){
                    range[0]=weekInfo;
                    range[1]=weekInfo;
                }
                    start = Integer.parseInt(range[0]);
                    end = Integer.parseInt(range[1]);
                if(start<0 || end>16){
                    errweekList.add(day);
                    continue;
                }
                for (int i = start; i <= end; i++) {
                    weeks.add(i);
                }
            }
            cource.setWeeks(weeks);
            // 提取节数
            String sectionInfo = weekParts[2];
            String[] sections = sectionInfo.split("-");
            int startSection = Integer.parseInt(sections[0]);
            int endSection = Integer.parseInt(sections[1]);
            if(startSection<1 || endSection>13){
                errweekList.add(day);
                continue;
            }
            cource.setStartSection(startSection);
            cource.setEndSection(endSection);
            courceList.add(cource);}
            catch(Exception e){
                errweekList.add(day);
            }
        }
        if(errweekList.size()>0){
            //合并errweekList中的相同元素相同的数字
           errweekList = errweekList.stream().distinct().collect(Collectors.toList());
        }
        //删除courceList中
        for (int i = 0; i < errweekList.size(); i++) {
            for (int j = 0; j < courceList.size(); j++) {
                if(courceList.get(j).getDayOfWeek()==errweekList.get(i)){
                    courceList.remove(j);
                    j--;
                }
            }
        }
        courceList.sort(Comparator.comparingInt(Cource::getDayOfWeek));
        int i=0;
        while (!(i==(courceList.size()-1))){
            List<Integer> collect=new ArrayList<>();
            Cource cource1 = courceList.get(i);
            Cource cource2 = courceList.get(i+1);
            if (cource1.getDayOfWeek() == cource2.getDayOfWeek() && cource1.getStartSection()==(cource2.getStartSection())){
                List<Integer> list1 = cource1.getWeeks();
                List<Integer> list2 = cource2.getWeeks();
                List<Integer> merged = new ArrayList<>();
                merged.addAll(list1);
                merged.addAll(list2);
                collect = merged.stream().sorted().collect(Collectors.toList());
                courceList.get(i).setWeeks(collect);
                courceList.get(i).setWeekType(0);
                //删除courceList中的第二个元素
                courceList.remove(i+1);
                i--;
            }
            i++;
        }
        //得到了所有课程信息
        ErrCources errCources = new ErrCources();
        errCources.setCources(courceList);
        errCources.setErrCourceIds(errweekList);
        return errCources;
    }
    public static List<String> splitString(String str) {
        List<String> parts = new ArrayList<>();
        int startIndex = 0;
        int weekIndex = 0;

        while ((weekIndex = str.indexOf("周", startIndex))!= -1) {
            int leftParenthesisIndex1 = str.lastIndexOf('（', weekIndex);
            int leftParenthesisIndex2 = str.lastIndexOf('(', weekIndex);
            int leftParenthesisIndex = Math.max(leftParenthesisIndex1, leftParenthesisIndex2);
            int sectionIndex = str.indexOf("节", weekIndex);

            if (leftParenthesisIndex!= -1 && sectionIndex!= -1) {
                String substring = str.substring(leftParenthesisIndex + 1, sectionIndex);
                //字符串byte大小不能超过100
                if(substring.getBytes().length<=30){
                    parts.add(substring);
                }

            }

            startIndex = weekIndex + 1;
        }

        return parts;
    }
    /**
     * 从扫描的图片文字获得学生学号
     */
    public static String extractNumber(String str) {
        // 匹配中文、英文的小括号
        Pattern pattern = Pattern.compile("[(（](20\\d{11})[)）]");
        Matcher matcher = pattern.matcher(str);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return null;
    }
}
